package com.aner.tester.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * data factory
 *
 * @author aner
 * @version 1.0
 * @date 2020/10/12 14:07
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    
    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", 
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"
    };
    /**
     * get current date string, like "yyyy-MM-dd"
     * 
     * @return
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    /**
     * get current date string, like "yyyy-MM-dd HH:MM:SS"
     *
     * @return
     */
    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    /**
     *get current date string, like "yyyyMMddHHMMSS"
     *
     * @return
     */
    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    /**
     * get date string, like "yyyyMMdd"
     *
     * @param date
     * @return
     */
    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }
    /**
     * format current date
     *
     * @param format
     * @return
     */
    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    /**
     * format date
     *
     * @param format
     * @param date
     * @return date string
     */
    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    /**
     * format date
     *
     * @param format
     * @param ts
     * @return date
     */
    public static final Date parseDate(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * format date string
     * @param str
     * @return
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }
}
